package com.yc.demo.d0304;

import javax.servlet.*;
import javax.servlet.annotation.*;
import java.io.IOException;

/**
 * 设置字符集编码
 * value表示过滤的资源路径
 *     *    表示0—n个字符  =》匹配多个地址
 */
@WebFilter(filterName = "EncodingFilter" ,value = "*.s")
public class EncodingFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        System.out.println("EncodingFilter 初始化");
    }

    public void destroy() {
        System.out.println("EncodingFilter 销毁");
    }

    @Override
    public void doFilter(
            //HttpServletRequest request, HttpServletResponse response
            ServletRequest request,//
            ServletResponse response,
            FilterChain chain)     //chain 过滤器对象
            throws ServletException, IOException {
        //字符集要尽早的设置
             request.setCharacterEncoding("utf-8");
             response.setCharacterEncoding("utf-8");
             //默认设置资源返回结果类型是json
             response.setContentType("application/json;charset=utf-8");

             chain.doFilter(request, response);
             System.out.println("EncodingFilter 执行过滤（后）");
    }
}
